﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using RoleBasedSecurity.Generics;

namespace RoleBasedSecurity
{
    public class Global : System.Web.HttpApplication
    {

        protected void Application_Start(object sender, EventArgs e)
        {

        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {

        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            try
            {
                HttpCookie cookie = Context.Request.Cookies.Get(FormsAuthentication.FormsCookieName);
                if (!IsNull(cookie))
                {
                    FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);                    
                    GIdentity _Identity = new GIdentity(ticket.Name, "Custom", true);
                    GPrincipal _Principal = new GPrincipal(_Identity, ticket.UserData.Split('|'));
                    Context.User = _Principal;
                }
                else
                {
                    return;
                }
            }
            catch (Exception ex)
            {
                return;
            }
        }

        protected void Application_Error(object sender, EventArgs e)
        {

        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {

        }

        bool IsNull(Object obj)
        {
            return obj == null ? true : false;
        }
    }
}